﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DevFx.FrameWork.Context
{
    /// <summary>
    /// 上下文
    /// </summary>
    internal class DefaultContext : IContext
    {
        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public DefaultContext()
        {
            dic = new Dictionary<string, object>();
        }

        //做分布式处理时，会需要使用该构造函数,暂时屏蔽
        ///// <summary>
        ///// 构造函数
        ///// </summary>
        ///// <param name="dic">字典项</param>
        //public DefaultContext(Dictionary<string, object> dic)
        //{
        //    this.dic = dic;
        //}

        #endregion

        #region 私有成员

        private IDictionary<string, object> dic;

        #endregion

        #region 实现的接口

        /// <summary>
        /// 是否包含该键值对象
        /// </summary>
        /// <param name="key">键值</param>
        /// <returns></returns>
        public bool Contains(string key)
        {
            return dic.ContainsKey(key);
        }

        /// <summary>
        /// 获取对象
        /// </summary>
        /// <param name="key">键值</param>
        /// <returns></returns>
        public object GetItem(string key)
        {
            return dic[key];
        }

        /// <summary>
        /// 获取上下文中所有的项集合
        /// </summary>
        /// <returns></returns>
        public IDictionary<string, object> Items
        {
            get
            {
                IDictionary<string, object> items = new Dictionary<string, object>();
                foreach (string key in dic.Keys)
                    items.Add(key, dic[key]);

                return items;
            }
        }


        /// <summary>
        /// 添加键值对
        /// </summary>
        /// <param name="key">键值</param>
        /// <param name="obj">对象</param>
        public void PutItem(string key, object obj)
        {
            if (dic.ContainsKey(key))
                dic.Remove(key);

            dic.Add(key, obj);
        }

        /// <summary>
        /// 删除项


        /// </summary>
        /// <param name="key">键值</param>
        public void Remove(string key)
        {
            if (dic.ContainsKey(key))
                dic.Remove(key);
        }

        #endregion
    }
}
